/*
 * @lc app=leetcode.cn id=8 lang=java
 *
 * [8] 字符串转换整数 (atoi)
 */

// @lc code=start
class Solution {

    public boolean isDigit(char c) {
        int ic = (int) c;

        return c >= (int) '0' && c <= (int) '9';
    }

    public int myAtoi(String s) {

        for(int i=0;i<s.length();i++){
            if(s.charAt(i)!=' '){
                s = s.substring(i);
                break;
            }
        }
        if (s.length() == 0)
            return 0;
        int flag = 1;
        if (s.charAt(0) == '-') {
            if(s.length()==1 || !isDigit(s.charAt(1))) return 0;
            flag = -1;
            s= s.substring(1);
        }else if(s.charAt(0)=='+'){
            if(s.length()==1 || !isDigit(s.charAt(1))) return 0;
            s= s.substring(1);
        }
        
        double bench = 0;
        for (char c : s.toCharArray()) {
            if (isDigit(c)) {
                bench = bench * 10 + (int) c - (int) '0';
            } else
                break;
        }
        bench*=flag;
        if(bench>Integer.MAX_VALUE) return Integer.MAX_VALUE;
        if(bench<Integer.MIN_VALUE) return Integer.MIN_VALUE;
        return (int)bench;

    }
}
// @lc code=end
